package cn.sdhuijin.vms.sms.web.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.swing.JOptionPane;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smslib.SMSLibException;
import org.smslib.Service;
import org.smslib.Service.ServiceStatus;
import org.smslib.TimeoutException;
import org.smslib.modem.SerialModemGateway;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.sdhuijin.vms.sms.callback.InboundMessageNotification;
import cn.sdhuijin.vms.sms.callback.OrphanedMessageNotification;
import cn.sdhuijin.vms.sms.callback.OutboundMessageNotification;
import cn.sdhuijin.vms.sms.callback.QueueSendingNotification;
import cn.sdhuijin.vms.sms.util.SmsUtil;

import com.mchange.v2.lang.StringUtils;

public class SmsServiceServlet implements Servlet {
	final Logger logger = LoggerFactory.getLogger(SmsServiceServlet.class);
	private ServletConfig config;
	private String COM_PORT = "COM1";
	private Integer baudRate = 9600;
	private String manufacturer = "";
	private String model = "";

	private Integer QUEUE_RETRIES = 1;
	private Integer OUTBOUND_RETRIES = 1;
	private Integer HOURS_TO_ORPHAN = 1;

	private WebApplicationContext ctx = null;

	@Override
	public void init(ServletConfig config) throws ServletException {
		this.config = config;
		ServletContext servletContext = config.getServletContext();

		this.ctx = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);

		String com_port = config.getInitParameter("COM_PORT").trim();
		this.COM_PORT = StringUtils.nonEmptyTrimmedOrNull(com_port) != null ? com_port
				: this.COM_PORT;

		SmsUtil.notifyPhone = config.getInitParameter("NOTIFI").trim();

		try {
			this.setModem();
		} catch (SMSLibException | IOException | InterruptedException e) {
			logger.error("短信猫设置失败.{}", e.toString());
			JOptionPane.showMessageDialog(null, "短信猫未启动。", "错误",
					JOptionPane.ERROR_MESSAGE);
		}

	}

	private void setModem() throws TimeoutException, SMSLibException,
			IOException, InterruptedException {
		logger.info("设置短信猫。com_port:{}", this.COM_PORT);
		SerialModemGateway gateway = new SerialModemGateway("modem1",
				this.COM_PORT, baudRate, manufacturer, model);
		gateway.setInbound(true);
		gateway.setOutbound(true);
		Service.getInstance().S.QUEUE_RETRIES = this.QUEUE_RETRIES;
		Service.getInstance().S.OUTBOUND_RETRIES = this.OUTBOUND_RETRIES;
		Service.getInstance().S.HOURS_TO_ORPHAN = this.HOURS_TO_ORPHAN;

		Service.getInstance().setInboundMessageNotification(
				this.ctx.getBean(InboundMessageNotification.class));
		Service.getInstance().setOutboundMessageNotification(
				this.ctx.getBean(OutboundMessageNotification.class));
		Service.getInstance().setOrphanedMessageNotification(
				this.ctx.getBean(OrphanedMessageNotification.class));
		Service.getInstance().setQueueSendingNotification(
				this.ctx.getBean(QueueSendingNotification.class));
		Service.getInstance().addGateway(gateway);
		Service.getInstance().startService();
		logger.info("短信猫启动成功。p:{}", this.COM_PORT);
	}

	@Override
	public ServletConfig getServletConfig() {
		return this.config;
	}

	@Override
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {

	}

	@Override
	public String getServletInfo() {
		return "短信猫web启动器";
	}

	@Override
	public void destroy() {
		logger.info("关闭短信猫。");
		try {
			if (Service.getInstance().getServiceStatus() == ServiceStatus.STARTED) {
				Service.getInstance().stopService();
			}

		} catch (Exception e) {
			logger.error(e.toString());
		}
	}

}
